package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishSercice;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1、保存套餐数据 setmeal
        this.save(setmealDto);

        //2、保存套餐菜品关系数据 setmeal_dish
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        //遍历设置每一个SetmealDish的setmeakId的值
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishSercice.saveBatch(setmealDishList);


    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        // 判断套餐是否正在售卖
        QueryWrapper<Setmeal> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in(ids.size()>0,"id",ids);
        queryWrapper1.eq("status",1);
        int count = this.count(queryWrapper1);
        if (count>0){
            throw new CustomException("套餐正在售卖，不能删除");
        }
        // 删除套餐
        this.removeByIds(ids);
        // 删除套餐数据
        QueryWrapper<SetmealDish> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("setmeal_id",ids);
        setmealDishSercice.remove(queryWrapper2);

    }
}
